import { optimizeCb } from '../core/optimizeCb'
import { isArrLike } from '../core/isArrLike'
import { isUndef } from '../core/isUndef'
import { keys } from '../core/keys'
//5710
/**
 * 类似es6 Array的reduce方法
 * reduce([1, 2, 3],function(sum, n) {return sum + n;}, 0); // -> 6
 * dependencies optimizeCb isArrLike isUndef keys
 * @param {*} obj 目标数组
 * @param {*} iterator 处理函数
 * @param {*} initial 初始值
 * @param {*} ctx 函数上下文
 */
export function reduce (obj, iterator, initial, ctx) {
  var dir = 1;
  iterator = optimizeCb(iterator, ctx);
  var i, len, key;

  if (isArrLike(obj)) {
    len = obj.length;
    i = dir > 0 ? 0 : len - 1;

    if (isUndef(initial)) {
      initial = obj[i];
      i += dir;
    }

    for (; i < len && i >= 0; i += dir) {
      initial = iterator(initial, obj[i], i, obj);
    }
  } else {
    var _keys = keys(obj);

    len = _keys.length;
    i = dir > 0 ? 0 : len - 1;

    if (isUndef(initial)) {
      initial = obj[_keys[i]];
      i += dir;
    }

    for (; i < len && i >= 0; i += dir) {
      key = _keys[i];
      initial = iterator(initial, obj[key], key, obj);
    }
  }

  return initial;
}